/* api */
import * as ProjectManageApi from '@src/api/ProjectManage';
/* entity */
import Field from '@model/entity/Field';
/* model */
import { systemFields, projectStatus, delayedTasksField } from '@src/modules/projectManage/projectManageList/model';
import MsgModel from '@model/MsgModel';
import Page from '@model/Page';
/* enum */
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
import TableNameEnum from '@model/enum/TableNameEnum';
/* util */
import { setProjectPageList } from '@src/modules/projectManage/projectManageList/util';
import { message } from '@src/util/message';
import { t } from '@src/locales';
import Log from '@src/util/log';
import { getRootWindow } from '@src/util/dom';
/* hooks */
import { useLoading } from '@hooks/useLoading';
/* vue */
import { Ref, reactive, ref } from 'vue';

import i18n from '@src/locales';

// 获取项目类型
function useFetchProjectTypeList() {
  // 项目类型
  const projectTypeList = ref([]);
    
  const fetchProjectTypeList = () => {
    const params = {
      status: 1,
    };

    return (
      ProjectManageApi.projectTypeList(params).then((res: any) => {
        if (MsgModel.isSuccess(res)) {
          const { data = [] } = res || {};

          projectTypeList.value = data.map((item: any) => {
            // 增加属性，方便视图筛选
            return {
              ...item,
              label: item.name,
              value: item.id
            }
          });

        } else {
          message.error(res.message);
        }
        
        return projectTypeList.value;

      }).catch((error: any) => {
        Log.error(error, fetchProjectTypeList.name);
      })
    )
  }
  
  return {
    projectTypeList,
    fetchProjectTypeList,
  }
}

// 标签灰度
function labelGrayFunc() {
  const RootWindow = getRootWindow(window)
  return RootWindow.grayAuth?.PROJECT_DELAY || false
}

// 获取项目类型字段列表
function useFetchProjectFieldList() {
  // 字段列表
  const fields = ref([] as Field[]);
    
  const fetchProjectFieldList = (templateId: string) => {
    return (
      ProjectManageApi.getProjectTypeField({ templateId, tableName: TableNameEnum.Project }).then(res => {
        if (MsgModel.isSuccess(res)) {
          // 合并固定系统字段、过滤连接器
  
          let allFields = [...res?.data || [], ...systemFields].filter((field: Field) => field.formType != FieldTypeMappingEnum.Connector && field.isHidden !== 1);

          allFields = labelGrayFunc() ? [...allFields, ...delayedTasksField] : [...allFields]

          fields.value = allFields.map((item: any) => {
            // 先把模板id去掉，不传到选择列组件里面，选择列组件对模板id做了处理
            const { templateId, ...other } = item;
            return other;
          });
        } else {
          message.error(res.message);
        }
        
        return fields.value;

      }).catch((error: any) => {
        Log.error(error, fetchProjectFieldList.name);
      })
    )
  }
  
  return {
    fields,
    fetchProjectFieldList,
  }
}

// 获取项目状态
function useFetchProjectStatusList() {
  const dataStatusList = ref([]);
    
  const fetchProjectStatusList = ({ templateId, searchType, viewType }) => {
    return (
      ProjectManageApi.getStatusStatisticList({ templateId, searchType, viewType }).then(res => {
        if (MsgModel.isSuccess(res)) {

          dataStatusList.value = (res?.result || [])
            .map((item: any) => {
              const status = projectStatus?.[item?.code] || item.name;

              if (item.code == 'ALL') item.code = '';
              
              // 增加属性，方便视图筛选
              return {
                ...item,
                label: status,
                value: item.code
              }
            });

        } else {
          message.error(res.message);
        }
        
        return dataStatusList.value;

      }).catch((error: any) => {
        Log.error(error, fetchProjectStatusList.name);
      })
    )
  }
  
  return {
    dataStatusList,
    fetchProjectStatusList,
  }
}

// 获取按钮权限
function useFetchProjectAuthButton() {
  const btnAuth = ref({});
    
  const fetchProjectAuthButton = () => {
    const params = {};

    return (
      ProjectManageApi.projectTypeRoleBtn(params).then(res => {
        if (MsgModel.isSuccess(res)) {

          btnAuth.value = res?.data || {};

        } else {
          message.error(res.message);
        }
        
        return btnAuth.value;

      }).catch((error: any) => {
        Log.error(error, fetchProjectAuthButton.name);
      })
    )
  }
  
  return {
    btnAuth,
    fetchProjectAuthButton,
  }
}

// 删除项目
function useFetchDeleteProject() {
  const fetchDeleteProject = (ids: any) => {
    return (
      ProjectManageApi.projectTypePageDelete(ids).then(res => {
        if (MsgModel.isSuccess(res)) {

          return Promise.resolve();

        } else {
          message.error(res.message);

          return Promise.reject();
        }

      }).catch((error: any) => {
        Log.error(error, fetchDeleteProject.name);

        return Promise.reject(error);
      })
    )
  }
  
  return {
    fetchDeleteProject,
  }
}

// 获取项目列表数据
function useFetchProjectTableList() {
  // 加载状态
  const { loading, showLoading, hideLoading } = useLoading();

  const dataList = ref([] as any[]);
  const dataListPageInfo: Ref<Page> = ref(new Page());
    
  const fetchProjectTableList = (searchParams: any) => {
    const translate = (code: string) => {
      const messages: any = {
        START: t("common.base.notStart"),
        RUN: t("common.base.processing"),
        COMPLETE: t("common.task.type.finished"),
        CANCEL: t("common.task.materialLackStockState.2"),
        default: t("common.projectManage.detail.allTypes"),
      };
      return messages[code] || messages.default;
    };
    
    showLoading();

    return (
      ProjectManageApi.getProjectTableList(searchParams).then(res => {
        if (MsgModel.isSuccess(res)) {
          
          dataListPageInfo.value = (res?.result || new Page()) as Page;

          dataList.value = setProjectPageList(res?.result?.list || []);
          dataList.value =  dataList.value.map(item => {
              const text = translate(item.projectStatusType)
              item = {...item,translateText : text}
              return item;
          })
        } else {
          message.error(res.message);
        }
        
        return dataList.value;

      }).catch((error: any) => {
        Log.error(error, fetchProjectTableList.name);
      }).finally(() => {
        hideLoading();
      })
    )
  }
  
  return {
    loading,
    dataList,
    dataListPageInfo,
    fetchProjectTableList,
  }
}

// 获取项目卡片模式列表数据
function useFetchProjectCardList() {

  // 根据状态将数据分组
  let dataGroup = reactive({} as any);
  
  const fetchProjectCardList = (searchParams: any) => {

    return (
      ProjectManageApi.getProjectCardList(searchParams).then(res => {
        if (MsgModel.isSuccess(res)) {

          (res?.result || []).forEach((item: any) => {
            // 唯一标识
            const key = item.statusType || item.statusId;
            
            // 该状态无数据时初始化
            if (!dataGroup[key]) dataGroup[key] = new Page();

            dataGroup[key].merge(Page.as(item?.dataList || new Page()));

            // 格式化列表数据
            dataGroup[key].list = setProjectPageList(dataGroup[key].list);
          })

          return Promise.resolve();

        } else {
          message.error(res.message);

          return Promise.reject();
        }

      }).catch((error: any) => {
        Log.error(error, fetchProjectCardList.name);

        return Promise.reject(error);
      })
    )
  }
  const resetDataGroup = () => {
    for (let key in dataGroup) {
      dataGroup[key] = new Page() as Page;
    }
  }
  
  return {
    dataGroup,
    resetDataGroup,
    fetchProjectCardList,
  }
}


  // 获取项目列表时间线数据
  function useFetchProjectTableTimelineList() {
    // 加载状态
    const { loading, showLoading, hideLoading } = useLoading();

    const dataList = ref([] as any[]);
    const dataListPageInfo: Ref<Page> = ref(new Page());
      
    const fetchProjectTableTimelineList = (searchParams: any) => {

      showLoading();

      return (
        ProjectManageApi.getProjectTimeLineList(searchParams).then(res => {
          if (MsgModel.isSuccess(res)) {
            
            dataListPageInfo.value = (res?.result || new Page()) as Page;

            dataList.value = setProjectPageList(res?.result?.list || []);

          } else {
            message.error(res.message);
          }
          
          return dataList.value;

        }).catch((error: any) => {
          Log.error(error, fetchProjectTableTimelineList.name);
        }).finally(() => {
          hideLoading();
        })
      )
    }
    
    return {
      loading,
      dataList,
      dataListPageInfo,
      fetchProjectTableTimelineList,
    }
  }

export {
  useFetchProjectTypeList,
  useFetchProjectFieldList,
  useFetchProjectStatusList,
  useFetchProjectAuthButton,
  useFetchDeleteProject,
  useFetchProjectTableList,
  useFetchProjectCardList,
  useFetchProjectTableTimelineList
}
